<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { showToast, showConfirmDialog } from 'vant'
import { taskApi } from '@/api'
import SimpleDatePicker from '@/components/SimpleDatePicker.vue'

const router = useRouter()
const route = useRoute()
const loading = ref(false)
const isEdit = ref(false)

// 表单数据 - 匹配后端数据库表结构
const form = ref({
  id: null,
  taskName: '',
  scopeType: 'SYSTEM',
  subscribeType: 'DATA',
  subscribeMode: 'RAW',
  dataFormat: 'CSV',
  dataSource: '日库',
  targetSystems: 'SYSTEM_A',
  customsCode: '',
  groupFields: '{}',
  numericAggFields: '{}',
  conditions: '{}',
  selectedFields: '["*"]',
  dataRange: 'ALL',
  strongCheck: 'N',
  status: 'ACTIVE',
  dispatchStatus: 'PENDING',
  closeDateStart: '',
  closeDateEnd: '',
  fileName: '',
  filePath: ''
})

// 选项数据
const scopeTypeOptions = [
  { text: '全量', value: 'FULL' },
  { text: '增量', value: 'INCREMENTAL' },
  { text: '指定范围', value: 'RANGE' }
]

const subscribeTypeOptions = [
  { text: '自动订阅', value: 'AUTO' },
  { text: '手动订阅', value: 'MANUAL' },
  { text: '定时订阅', value: 'SCHEDULED' }
]

const subscribeModeOptions = [
  { text: '原始数据', value: 'RAW' },
  { text: '汇总数据', value: 'AGG' }
]

const dataFormatOptions = [
  { text: 'CSV', value: 'CSV' },
  { text: 'TXT', value: 'TXT' },
  { text: 'EXCEL', value: 'EXCEL' },
  { text: '331格式', value: '331' }
]

const dataSourceOptions = [
  { text: '日库', value: '日库' },
  { text: '月库', value: '月库' },
  { text: '发布', value: '发布' }
]

const strongCheckOptions = [
  { text: '否', value: 'N' },
  { text: '是', value: 'Y' }
]

const dataRangeOptions = [
  { text: '全部', value: 'ALL' },
  { text: '当日', value: 'TODAY' },
  { text: '当月', value: 'CURRENT_MONTH' },
  { text: '自定义', value: 'CUSTOM' }
]

const statusOptions = [
  { text: '激活', value: 'ACTIVE' },
  { text: '停用', value: 'INACTIVE' }
]

const dispatchStatusOptions = [
  { text: '待处理', value: 'PENDING' },
  { text: '处理中', value: 'PROCESSING' },
  { text: '已完成', value: 'COMPLETED' },
  { text: '失败', value: 'FAILED' }
]

// 系统选项（示例）
const systemOptions = [
  { text: '系统A', value: 'SYSTEM_A' },
  { text: '系统B', value: 'SYSTEM_B' },
  { text: '系统C', value: 'SYSTEM_C' }
]

// 字段选项（示例）
const fieldOptions = [
  { text: '报关单号', value: 'entry_id' },
  { text: '商品序号', value: 'g_no' },
  { text: '进出口标志', value: 'i_e_flag' },
  { text: '贸易方式', value: 'trade_mode' },
  { text: '运输方式', value: 'trans_mode' }
]

// 加载任务详情（编辑模式）
const loadTask = async () => {
  if (!route.params.id) return

  loading.value = true
  try {
    const task = await taskApi.getTaskById(route.params.id)

    // 填充表单数据，处理字符串字段转数组
    form.value = {
      ...task,
      targetSystems: task.targetSystems ? task.targetSystems.split(',').filter(s => s.trim()) : [],
      groupFields: task.groupFields ? task.groupFields.split(',').filter(s => s.trim()) : [],
      selectedFields: task.selectedFields ? task.selectedFields.split(',').filter(s => s.trim()) : [],
      closeDateStart: task.closeDateStart || '',
      closeDateEnd: task.closeDateEnd || ''
    }
  } catch (error) {
    showToast('加载失败: ' + error.message)
    router.back()
  } finally {
    loading.value = false
  }
}

// 保存任务
const saveTask = async () => {
  // 必填字段验证
  if (!form.value.taskName.trim()) {
    showToast('请输入任务名称')
    return
  }

  if (!form.value.scopeType) {
    showToast('请选择范围类型')
    return
  }

  if (!form.value.subscribeType) {
    showToast('请选择订阅类型')
    return
  }

  if (!form.value.subscribeMode) {
    showToast('请选择订阅模式')
    return
  }

  if (!form.value.dataFormat) {
    showToast('请选择数据格式')
    return
  }

  if (!form.value.dataSource) {
    showToast('请选择数据源')
    return
  }

  if (!form.value.customsCode || !form.value.customsCode.trim()) {
    showToast('请输入关区代码')
    return
  }

  loading.value = true
  try {
    // 提交所有数据库表字段
    const data = {
      id: form.value.id || null,
      taskName: form.value.taskName.trim(),
      scopeType: form.value.scopeType,
      subscribeType: form.value.subscribeType,
      subscribeMode: form.value.subscribeMode,
      dataFormat: form.value.dataFormat,
      dataSource: form.value.dataSource,
      targetSystems: form.value.targetSystems || '',
      customsCode: form.value.customsCode.trim(),
      groupFields: form.value.groupFields || '{}',
      numericAggFields: form.value.numericAggFields || '{}',
      conditions: form.value.conditions || '{}',
      selectedFields: form.value.selectedFields || '["*"]',
      dataRange: form.value.dataRange || 'ALL',
      strongCheck: form.value.strongCheck || 'N',
      status: form.value.status || 'ACTIVE',
      dispatchStatus: form.value.dispatchStatus || 'PENDING',
      closeDateStart: form.value.closeDateStart || null,
      closeDateEnd: form.value.closeDateEnd || null,
      fileName: form.value.fileName || '',
      filePath: form.value.filePath || ''
    }

    await taskApi.saveTask(data)
    showToast(isEdit.value ? '更新成功' : '创建成功')
    router.back()
  } catch (error) {
    showToast('保存失败: ' + error.message)
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  isEdit.value = !!route.params.id
  if (isEdit.value) {
    loadTask()
  }
})
</script>

<template>
  <div class="page-container">
    <van-nav-bar
      :title="isEdit ? '编辑任务' : '新建任务'"
      left-arrow
      @click-left="router.back()"
    />

    <van-form @submit="saveTask">
      <van-cell-group inset>
        <van-field
          v-model="form.taskName"
          name="taskName"
          label="任务名称"
          placeholder="请输入任务名称"
          :rules="[{ required: true, message: '请输入任务名称' }]"
        />

        <van-field name="scopeType" label="范围类型" :rules="[{ required: true, message: '请选择范围类型' }]">
          <template #input>
            <van-radio-group v-model="form.scopeType" direction="horizontal">
              <van-radio
                v-for="option in scopeTypeOptions"
                :key="option.value"
                :name="option.value"
              >
                {{ option.text }}
              </van-radio>
            </van-radio-group>
          </template>
        </van-field>

        <van-field name="subscribeType" label="订阅类型" :rules="[{ required: true, message: '请选择订阅类型' }]">
          <template #input>
            <van-radio-group v-model="form.subscribeType" direction="horizontal">
              <van-radio
                v-for="option in subscribeTypeOptions"
                :key="option.value"
                :name="option.value"
              >
                {{ option.text }}
              </van-radio>
            </van-radio-group>
          </template>
        </van-field>

        <!-- 目标系统选择 -->
        <van-field name="targetSystems" label="目标系统">
          <template #input>
            <van-radio-group v-model="form.targetSystems" direction="horizontal">
              <van-radio
                v-for="option in systemOptions"
                :key="option.value"
                :name="option.value"
              >
                {{ option.text }}
              </van-radio>
            </van-radio-group>
          </template>
        </van-field>

        <!-- 关区代码：后端必填，始终展示 -->
        <van-field
          v-model="form.customsCode"
          name="customsCode"
          label="关区代码"
          placeholder="请输入关区代码（如：0300）"
          :rules="[{ required: true, message: '请输入关区代码' }]"
        />

        <van-field name="subscribeMode" label="订阅模式" :rules="[{ required: true, message: '请选择订阅模式' }]">
          <template #input>
            <van-radio-group v-model="form.subscribeMode" direction="horizontal">
              <van-radio
                v-for="option in subscribeModeOptions"
                :key="option.value"
                :name="option.value"
              >
                {{ option.text }}
              </van-radio>
            </van-radio-group>
          </template>
        </van-field>

        <van-field name="dataFormat" label="数据格式" :rules="[{ required: true, message: '请选择数据格式' }]">
          <template #input>
            <van-radio-group v-model="form.dataFormat" direction="horizontal">
              <van-radio
                v-for="option in dataFormatOptions"
                :key="option.value"
                :name="option.value"
              >
                {{ option.text }}
              </van-radio>
            </van-radio-group>
          </template>
        </van-field>

        <van-field name="dataSource" label="数据源" :rules="[{ required: true, message: '请选择数据源' }]">
          <template #input>
            <van-radio-group v-model="form.dataSource" direction="horizontal">
              <van-radio
                v-for="option in dataSourceOptions"
                :key="option.value"
                :name="option.value"
              >
                {{ option.text }}
              </van-radio>
            </van-radio-group>
          </template>
        </van-field>

        <van-field name="dataRange" label="数据范围">
          <template #input>
            <van-radio-group v-model="form.dataRange" direction="horizontal">
              <van-radio
                v-for="option in dataRangeOptions"
                :key="option.value"
                :name="option.value"
              >
                {{ option.text }}
              </van-radio>
            </van-radio-group>
          </template>
        </van-field>

        <van-field name="strongCheck" label="强校验">
          <template #input>
            <van-radio-group v-model="form.strongCheck" direction="horizontal">
              <van-radio
                v-for="option in strongCheckOptions"
                :key="option.value"
                :name="option.value"
              >
                {{ option.text }}
              </van-radio>
            </van-radio-group>
          </template>
        </van-field>

        <van-field name="status" label="任务状态">
          <template #input>
            <van-radio-group v-model="form.status" direction="horizontal">
              <van-radio
                v-for="option in statusOptions"
                :key="option.value"
                :name="option.value"
              >
                {{ option.text }}
              </van-radio>
            </van-radio-group>
          </template>
        </van-field>

        <van-field name="dispatchStatus" label="分发状态">
          <template #input>
            <van-radio-group v-model="form.dispatchStatus" direction="horizontal">
              <van-radio
                v-for="option in dispatchStatusOptions"
                :key="option.value"
                :name="option.value"
              >
                {{ option.text }}
              </van-radio>
            </van-radio-group>
          </template>
        </van-field>

        <SimpleDatePicker
          v-model="form.closeDateStart"
          label="结关开始日期"
          placeholder="请选择开始日期"
          title="选择开始日期"
        />

        <SimpleDatePicker
          v-model="form.closeDateEnd"
          label="结关结束日期"
          placeholder="请选择结束日期"
          title="选择结束日期"
        />

        <!-- 文件信息 -->
        <van-field
          v-model="form.fileName"
          name="fileName"
          label="文件名"
          placeholder="请输入文件名（可选）"
        />

        <van-field
          v-model="form.filePath"
          name="filePath"
          label="文件路径"
          placeholder="请输入文件路径（可选）"
        />

        <!-- 高级选项 -->
        <van-field
          v-model="form.groupFields"
          name="groupFields"
          label="汇总字段"
          type="textarea"
          placeholder="请输入汇总字段配置（JSON格式，如：{}）"
          rows="2"
        />

        <van-field
          v-model="form.numericAggFields"
          name="numericAggFields"
          label="数值聚合字段"
          type="textarea"
          placeholder="请输入数值聚合字段配置（JSON格式，如：{}）"
          rows="2"
        />

        <van-field
          v-model="form.conditions"
          name="conditions"
          label="统计条件"
          type="textarea"
          placeholder="请输入统计条件（JSON格式，如：{}）"
          rows="2"
        />

        <van-field
          v-model="form.selectedFields"
          name="selectedFields"
          label="选择字段"
          type="textarea"
          placeholder="请输入选择字段配置（JSON格式，如：['*']）"
          rows="2"
        />
      </van-cell-group>

      <div style="margin: 16px;">
        <van-button
          round
          block
          type="primary"
          native-type="submit"
          :loading="loading"
        >
          {{ isEdit ? '更新' : '创建' }}
        </van-button>
      </div>
    </van-form>
  </div>
</template>

<style scoped>
.van-cell-group {
  margin-bottom: 12px;
}
</style>
